import * as types from '../constraint/app.js'
import { fullWidthLayout, halfWidthLayout, customerLayout } from '../common/autoLayout.js'
import {remove} from 'lodash';
const initialState = []
const FilterSourceData = (sourceInfo) => {
  let data = sourceInfo.data
  let filters = sourceInfo.filters
  // field display exist 
  filters.forEach(a => {
    data = data.filter(row => a.members.length==0?true:-1 !== a.members.indexOf(row[a.field]))
  })
  return data
}
export default function app (state = initialState , action) {
  switch (action.type) {
    case types.RE_LAYOUT:
      return customerLayout(action.oldValue)
    case types.LOAD_SUCCESS:
      action.data.charts.forEach(a => {
        a.option.name = a.name
      })

      action.data.shouldUpdate = true
      return customerLayout(action.data)
    case types.SELECT_LEGEND_CHANGE:
      state.charts.forEach(a => {
        a.option.legendSelect = action.selectStatus
      })

      //state.sourceInfo.filterData = FilterSourceData(state.sourceInfo)
      state.shouldUpdate = true
      state.charts.forEach(a => a.shouldUpdate = true)
      return customerLayout(Object.assign({}, state))
    case types.SOURCE_FILTER:
      let field = action.data.field
      let value = action.data.member
      let type = action.data.type
      let selectFilter = state.sourceInfo.filters.filter(a => a.field == field)
      if (selectFilter && selectFilter.length > 0) { // 改维度对应的成员存在
        if (-1 === selectFilter[0].members.indexOf(value)) { // 不存在
           type=="apply"&&selectFilter[0].members.push(value)   //不存在 且类型为apply
        }else {
          //存在
          type=="detach"&&remove(selectFilter[0].members,(a)=>{return a==value;})   //不存在 且类型为detach
        }
      }else {
        state.sourceInfo.filters.push({field,members: [value]})
      }

      state.sourceInfo.filterData = FilterSourceData(state.sourceInfo)
      state.shouldUpdate = true
      state.charts.forEach(a => a.shouldUpdate = true)
      return state
    case types.LOAD_FAIL:
      return {}
      break
    case types.DATA_ACTIVE_STATUS:
      action.modifiDataUpdate.charts.forEach(setting => {
        setting.shouldUpdate = false
      })
      return action.modifiDataUpdate
    default:
      return state
  }
}
